<script setup lang="ts">
import { ref } from 'vue'
import { showLoadingToast, type ActionSheetAction } from 'vant'
import { request } from '@/utils/http'
import b64toBlob from 'b64-to-blob'
import { showToast } from 'vant'

const showSelectImg = ref(false) // 数据会变化 且变化后需要影响页面
const actions = [{ name: '选择照片' }, { name: '拍照' }]
const onSelect = async (action: ActionSheetAction, index: number) => {
  // console.log(item)
  showSelectImg.value = false // 关闭弹层

  if (index == 0) {
    console.log('选择照片')
    // 宿主环境: 浏览器 没有这个能力/ 原生侧(鸿蒙/安卓/IOS) 有这个能力
    const res = await MKMK.pickerPhoto() // 让你选照片  处理成base64
    console.log('选中的照片', res)
    // 待会上传
    uploadImg(res)
  } else {
    console.log('拍照')
    const res = await MKMK.pickerCamera() // 拍照片  处理成base64
    console.log('拍照片', res)
    // 待会上传
    uploadImg(res)
  }
}

/**
 * 上传base64图片到指定服务器
 * @param res base64字符串图片
 */
async function uploadImg(res: string) {
  // 参加一个FormData数据
  const fd = new FormData() // 空数据
  const blob = b64toBlob(res, 'image/jpeg') // 将base64 转 blob       参数2: 指定类型是图片
  fd.append('file', blob, Date.now() + '.jpeg') //  参数3: 指定图片的完整名  1231321312432.jpeg

  // 打开一个遮盖全屏loading
  showLoadingToast({
    message: '正在上传....',
    duration: 0,
    forbidClick: true // showLoadingToast过程中严禁点击其他区域
  })

  // 上传更新头像
  const temp = await request.post<MkResponse<{ avatar: string }>>('/member/profile/avatar', fd) // 把最新的头像信息给你了

  showToast('头像上传成功') // 顶掉之前那toast

  console.log(temp.data.result.avatar)
  profile.value.avatar = temp.data.result.avatar // 更新页面

  // 更新原生侧(原生侧的页面展示就是基于appstorage)
  const user = MKMK.queryUser() // 本来信息
  user.avatar = temp.data.result.avatar // 头像改了
  MKMK.updateUser(user)
}

const showSelectBirth = ref(false)

interface ResType {
  selectedValues: string[]
}

const confirmBirth = (res: ResType) => {
  // 选中生日后 点击确认
  // console.log(res.selectedValues.join('-'))
  profile.value.birthday = res.selectedValues.join('-') // 选中的生日赋值给profile
  // 关闭
  showSelectBirth.value = false
  // 待会需要向后端更新生日
}

const showSelectArea = ref(false)

// 需要获取省市区数据(原生侧提供了)
const list = MKMK.getAreaColumns() // 响应式数据
console.log(list)

const confirmArea = (res: ResType) => {
  console.log(res.selectedValues) // 选中的省市区编码  等会传后端

  // res.selectedValues[0] // 省编码
  // list.province_list // 所有省信息

  const sheng = list.province_list[Number(res.selectedValues[0])]
  const shi = list.city_list[Number(res.selectedValues[1])]
  const qu = list.county_list[Number(res.selectedValues[2])]
  console.log(sheng, shi, qu)

  profile.value.fullLocation = `${sheng} ${shi} ${qu}` // 完整地址

  // 接口额外还需要省市区的编码
  profile.value.provinceCode = Number(res.selectedValues[0])
  profile.value.cityCode = Number(res.selectedValues[1])
  profile.value.countyCode = Number(res.selectedValues[2])

  showSelectArea.value = false // 关闭
}

const showSelectJob = ref(false)

const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
  { text: '煤老板', value: '煤老板' },
  { text: '奥特曼', value: '奥特曼' }
]

const confirmJob = (res: ResType) => {
  showSelectJob.value = false // 关闭
  // 拿到选中的职业
  console.log(res.selectedValues[0]) // 等会向后端更新职业
  profile.value.profession = res.selectedValues[0]
}

const profile = ref<ProfileInfo>({} as ProfileInfo)
async function getProfile() {
  const res = await request.get<MkResponse<ProfileInfo>>('/member/profile')
  console.log(res.data.result)
  profile.value = res.data.result

  // 赋值职业给selectedJob
  selectedJob.value = [profile.value.profession]
  selectedBirth.value = profile.value.birthday.split('-')
}
getProfile()

const selectedJob = ref<string[]>([])

const selectedBirth = ref(['2021', '01', '01'])

const buttonLoading = ref(false)
// 保存资料
const submitServer = async () => {
  console.log(profile.value)

  // 震动
  MKMK.vibrator()

  // loading打开  转圈
  buttonLoading.value = true

  await request.put('/member/profile', profile.value) // 保存到服务端

  // 关闭loading
  buttonLoading.value = false

  // 更新原生侧
  const user = MKMK.queryUser()
  user.nickname = profile.value.nickname
  MKMK.updateUser(user)

  // 提示
  showToast('保存成功')
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- <van-button type="primary">主要按钮</van-button>
    <van-button type="success">成功按钮</van-button>
    <van-button type="default">默认按钮</van-button>
    <van-button type="danger">危险按钮</van-button>
    <van-button type="warning">警告按钮</van-button>
    <van-progress percentage="90" :stroke-width="20" color="#8df" track-color="#000" />
    <van-count-down :time="time" />
    <button>你好</button> -->
    <div class="avatar">
      <!-- <img src="" alt="" /> -->
      <van-image
        @click="showSelectImg = true"
        width="100"
        height="100"
        :round="true"
        class="avatar-img"
        :src="profile.avatar"
      ></van-image>
      <div class="avatar-btn">
        <span @click="showSelectImg = true">修改头像</span>
      </div>
    </div>

    <van-cell-group>
      <!-- <van-cell title="账号" value="内容" /> -->
      <!-- 输入框 -->
      <van-field v-model="profile.account" label="账号" :readonly="true" />
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称" />
      <!-- <van-cell title="单元格" value="内容" /> -->

      <van-cell title="性别" class="gender">
        <!-- 给组件提供结构 - 插槽 -->
        <van-radio-group v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>

      <van-field
        label="生日"
        v-model="profile.birthday"
        @click="showSelectBirth = true"
        placeholder="请输入生日"
        readonly
      />
      <van-field
        label="所在地"
        v-model="profile.fullLocation"
        @click="showSelectArea = true"
        placeholder="请输入所在地"
        :readonly="true"
      />
      <van-field
        label="职业"
        v-model="profile.profession"
        @click="showSelectJob = true"
        placeholder="请输入职业"
        :readonly="true"
      />
    </van-cell-group>

    <div class="submit">
      <van-button
        :loading="buttonLoading"
        type="primary"
        :block="true"
        :round="true"
        @click="submitServer"
      >
        保存资料
      </van-button>
    </div>

    <!-- 修改头像的弹层 -->
    <van-action-sheet
      cancel-text="再见"
      v-model:show="showSelectImg"
      :actions="actions"
      @select="onSelect"
    />

    <!-- 修改生日的弹层 -->
    <van-popup v-model:show="showSelectBirth" position="bottom" :round="true">
      <!-- <div>123</div> -->
      <van-date-picker
        v-model="selectedBirth"
        title="选择日期"
        @cancel="showSelectBirth = false"
        @confirm="confirmBirth"
      />
    </van-popup>

    <!-- 修改所在地的弹层 -->
    <van-popup v-model:show="showSelectArea" position="bottom" :round="true">
      <!-- <div>所在地的弹层</div> -->

      <!-- 组件直接展示所在地 -->
      <van-area
        title="所在地"
        :area-list="list"
        @cancel="showSelectArea = false"
        @confirm="confirmArea"
      />
    </van-popup>

    <!-- 修改职业的弹层 -->
    <van-popup v-model:show="showSelectJob" position="bottom" :round="true">
      <!-- <div>zhiye 的弹层</div> -->
      <van-picker
        title="职业"
        v-model="selectedJob"
        :columns="columns"
        @confirm="confirmJob"
        @cancel="showSelectJob = false"
      />

      <!-- 组件直接展示所在地 -->
    </van-popup>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
